package com.ruoyi.web.controller.scores;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.ObjectUtil;
import com.ruoyi.common.vo.PageResult;
import com.ruoyi.exam.domain.ExamScores;
import com.ruoyi.exam.serive.IExamScoreService;
import com.ruoyi.exam.serive.IScoresService;
import com.ruoyi.exam.vo.*;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.exam.vo.ExamScoresVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/scores")
public class ScoresController extends BaseController {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private IScoresService scoreService;



    //科目成绩（每个课程的成绩）
    @GetMapping("/course/list")
    @PreAuthorize("@ss.hasPermi('scores:course:list')")
    public TableDataInfo courseList(ScoresCourseVO scoresCourseVO){
        scoresCourseVO.setDelFlag(0);
        scoresCourseVO.setReleaseStatus(0);
        startPage();
        List<ScoresCourseVO> list = scoreService.selectScoresCourseList(scoresCourseVO);
        return getDataTable(list);
    }
    @PostMapping("/course/del")
    @PreAuthorize("@ss.hasPermi('scores:course:remove')")
    public AjaxResult delScoresCourse(@RequestBody ScoresCourseVO scoresCourseVO){
        ObjectUtil.checkNull(scoresCourseVO.getUserId(),"用户ID为空");
        ObjectUtil.checkNull(scoresCourseVO.getCourseNo(),"课程编号为空");
        scoreService.deleteCourseStudent(scoresCourseVO.getUserId(),scoresCourseVO.getCourseNo());
        return AjaxResult.success();
    }


    //单元成绩（课程分类的成绩，按每一科的成绩按百分比相加）
    @GetMapping("/coursetype/list")
    @PreAuthorize("@ss.hasPermi('scores:coursetype:list')")
    public TableDataInfo coursetypeList(ScoresCourseTypeVO scoresCourseVO){
        scoresCourseVO.setDelFlag(0);
        scoresCourseVO.setReleaseStatus(0);
        startPage();
        List<ScoresCourseTypeVO> list = scoreService.selectScoresCourseTypeList(scoresCourseVO);
        return getDataTable(list);
    }

    //理论成绩
    @GetMapping("/theory/list")
    @PreAuthorize("@ss.hasPermi('scores:theory:list')")
    public TableDataInfo theoryList(ScoresTheoryVO scoresTheoryVO){
        startPage();
        List<ScoresTheoryVO> list = scoreService.selectScoresTheoryList(scoresTheoryVO);
        return getDataTable(list);
    }
    @PostMapping("/theory/del")
    @PreAuthorize("@ss.hasPermi('scores:theory:remove')")
    public AjaxResult delScoresTheory(@RequestBody ScoresTheoryVO scoresTheoryVO){
        ObjectUtil.checkNull(scoresTheoryVO.getUserId(),"用户ID为空");
        ObjectUtil.checkNull(scoresTheoryVO.getPaperId(),"试卷为空");
        scoreService.deleteScoresTheory(scoresTheoryVO.getUserId(),scoresTheoryVO.getPaperId());
        return AjaxResult.success();
    }

    //综合成绩（综合成绩=期末成绩60%（期末成绩=理论30%+实操70%）+原理示教单元测试20%+体验操作单元测试20%；）
    @GetMapping("/combine/list")
    @PreAuthorize("@ss.hasPermi('scores:combine:list')")
    public TableDataInfo combineList(ScoresCombineVO scoresCombineVO){
        scoresCombineVO.setPaperId(1L); //写死试卷ID是1
        return combineScores(scoresCombineVO);
    }

    public TableDataInfo combineScores(ScoresCombineVO scoresCombineVO) {
        startPage();
        SysUser sysUser = new SysUser();
        sysUser.setUserId(scoresCombineVO.getUserId());
        sysUser.setUserName(scoresCombineVO.getUserName());
        sysUser.setNickName(scoresCombineVO.getNickName());
        List<SysUser> userList = userService.listUsers(sysUser);
        //
        TableDataInfo dataInfo = getDataTable(userList);
        if (CollectionUtils.isEmpty(userList)) {
            return dataInfo;
        }
        //
        List<Long> userIds = new ArrayList<>();
        userList.forEach(item -> {
            userIds.add(item.getUserId());
        });
        //获取理论成绩
        ScoresTheoryVO scoresTheoryVO = new ScoresTheoryVO();
        scoresTheoryVO.setUserIds(userIds);
        scoresTheoryVO.setPaperId(scoresCombineVO.getPaperId());
        scoresTheoryVO.setPaperName(scoresCombineVO.getPaperName());
        List<ScoresTheoryVO> scoresTheoryVOs = scoreService.selectScoresTheoryList(scoresTheoryVO);
        //获取实操成绩
        ScoresRealVO scoresRealVO = new ScoresRealVO();
        scoresRealVO.setUserIds(userIds);
        List<ScoresRealVO> scoresRealVOs = scoreService.selectScoresRealList(scoresRealVO);
        //获取单元成绩
        ScoresCourseTypeVO scoresCourseTypeVO = new ScoresCourseTypeVO();
        scoresCourseTypeVO.setDelFlag(0);
        scoresCourseTypeVO.setReleaseStatus(0);
        scoresCourseTypeVO.setUserIds(userIds);
        List<ScoresCourseTypeVO> scoresCourseTypeVOs = scoreService.selectScoresCourseTypeList(scoresCourseTypeVO);
        //开始计算
        List<ScoresCombineVO> combineVOList = new ArrayList<>();
        userList.forEach(item -> {
            //理论成绩
            List<ScoresTheoryVO> theoryVOList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(scoresTheoryVOs)) {
                for (ScoresTheoryVO vo : scoresTheoryVOs) {
                    if (item.getUserId() != null && vo.getUserId() != null &&
                            item.getUserId().longValue() == vo.getUserId().longValue()) {
                        theoryVOList.add(vo);
                    }
                }
            }
            //实操成绩
            ScoresRealVO realVO = null;
            if (!CollectionUtils.isEmpty(scoresRealVOs)) {
                for (ScoresRealVO vo : scoresRealVOs) {
                    if (item.getUserId() != null && vo.getUserId() != null &&
                            item.getUserId().longValue() == vo.getUserId().longValue()) {
                        realVO = vo;
                    }
                }
            }
            //原理示教、操作体验
            ScoresCourseTypeVO exampleScoresCourseTypeVO = null;
            ScoresCourseTypeVO operatorScoresCourseTypeVO = null;
            if (!CollectionUtils.isEmpty(scoresCourseTypeVOs)) {
                for (ScoresCourseTypeVO vo : scoresCourseTypeVOs) {
                    if (item.getUserId() != null && vo.getUserId() != null &&
                            item.getUserId().longValue() == vo.getUserId().longValue()) {
                        //原理示教
                        if (vo.getCourseType() != null && vo.getCourseType() == 1) {
                            exampleScoresCourseTypeVO = vo;
                        }
                        if (vo.getCourseType() != null && vo.getCourseType() == 2) {
                            operatorScoresCourseTypeVO = vo;
                        }
                    }
                }
            }
            //
            ScoresCombineVO combineVO = new ScoresCombineVO();
            combineVO.setUserId(item.getUserId());
            combineVO.setUserName(item.getUserName());
            combineVO.setNickName(item.getNickName());
            //
            combineVO.setTheoryScores(0L);
            combineVO.setRealScores(realVO == null ? 0L : realVO.getScores());
            combineVO.setExamineScores(0L);
            combineVO.setExampleScores(exampleScoresCourseTypeVO == null ? 0L : exampleScoresCourseTypeVO.getScores());
            combineVO.setOperatorScores(operatorScoresCourseTypeVO == null ? 0L : operatorScoresCourseTypeVO.getScores());
            combineVO.setCombineScores(0L);
            //综合成绩 = 期末成绩60% + 原理示教单元测试20% + 体验操作单元测试20%
            //期末成绩/考核评估 = 理论30%+实操70%
            // 理论成绩 、 实操成绩 、 期末成绩 、 原理示教成绩  、  体验操作成绩 、 综合成绩
            List<ScoresCombineVO> vos = new ArrayList<>();
            if (CollectionUtils.isEmpty(theoryVOList)) { //无理论考核
                vos.add(combineVO);
            } else {
                for ( ScoresTheoryVO vo : theoryVOList) {
                    ScoresCombineVO tmpVO = new ScoresCombineVO();
                    BeanUtil.copyProperties(combineVO,tmpVO,false);
                    tmpVO.setPaperId(vo.getPaperId());
                    tmpVO.setPaperName(vo.getPaperName());
                    tmpVO.setTheoryScores(vo.getScores());
                    vos.add(tmpVO);
                }
            }
            //计算
            for (ScoresCombineVO vo : vos) {
                vo.setExamineScores((long)(vo.getTheoryScores()*0.3f) + (long)(vo.getRealScores() * 0.7f)); //期末成绩
                vo.setCombineScores((long)(vo.getExamineScores()*0.6f) + (long)(vo.getExampleScores()*0.2f)+(long)(vo.getOperatorScores()*0.2f));
            }
            combineVOList.addAll(vos);
        });
        dataInfo.setRows(combineVOList);
        return dataInfo;
    }

}
